//
// Original code taken from Andy Pennell's blog at
// http://blogs.msdn.com/b/andypennell/archive/2010/11/01/error-reporting-on-windows-phone-7.aspx
//

using EmperialApps.WeatherSpark.Agent;
using EmperialApps.WeatherSpark.Internal;
using EmperialApps.WeatherSpark.Resources;
using Microsoft.Phone.Tasks;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.ServiceModel;
using System.Windows;

namespace EmperialApps.WeatherSpark.Helpers {

    using ErrorFileInfo = KeyValuePair<string, Localized.ErrorSource>;

    internal static class LittleWatson {

        public static void RecordException( Exception error, string header, string footer, IEnumerable<string> log ) {
            try {
                using( var store = IsolatedStorageFile.GetUserStoreForApplication( ) ) {
                    SafeDeleteFile( store, FileName );
                    using( TextWriter output = new StreamWriter( store.CreateFile( FileName ) ) ) {
                        output.WriteLine( header );

                        for( Exception ex = error; ex != null; ex = ex.InnerException ) {
                            string exceptionType = ex.GetType( ).Name;
                            if( !ex.Message.Contains( exceptionType ) )
                                output.Write( "[{0}] ", exceptionType );
                            output.WriteLine( ex.Message );

                            output.WriteLine( ex.StackTrace );

                            var fault = ex as FaultException<ExceptionDetail>;
                            if( fault != null ) {
                                output.WriteLine( Separator );
                                output.WriteLine( fault.Detail.StackTrace );
                            }

                            output.WriteLine( Separator );
                        }

                        output.WriteLine( footer );

                        output.WriteLine( Separator );
                        foreach( string line in log )
                            output.WriteLine( line );
                    }
                }
            }
            catch( Exception ) { }
        }

        public static void CheckForPreviousException( Localized.ErrorSource? source = null ) {
            try {
                string contents = null;
                Localized.ErrorSource? fileSource = null;
                using( var store = IsolatedStorageFile.GetUserStoreForApplication( ) )
                    foreach( ErrorFileInfo info in Files ) {
                        string fileName = info.Key;
                        if( store.FileExists( fileName ) ) {
                            if( contents != null )
                                contents += Environment.NewLine + Separator + Environment.NewLine;

                            try {
                                using( TextReader reader = new StreamReader( store.OpenFile( fileName, FileMode.Open, FileAccess.Read, FileShare.None ) ) )
                                    contents += reader.ReadToEnd( );
                                fileSource = fileSource ?? info.Value;
                            }
                            catch( Exception ) { }

                            SafeDeleteFile( store, fileName );
                        }
                    }

                if( !string.IsNullOrEmpty( contents ) ) {
                    string sourceId = (source ?? fileSource).ToString( );
                    string sourceMessage = AppResources.ResourceManager.GetString( "ErrorSource_" + sourceId ) ?? sourceId;
                    var result = Localized.Popup.ProblemReport.Ask( sourceMessage );
                    if( result == MessageBoxResult.OK ) {
                        string body =
                            source == null
                                ? contents
                                : "What: " + source + Environment.NewLine + contents;
                        var email = new EmailComposeTask { To = EmailAddress, Subject = AppName + " auto-generated problem report", Body = body };
                        SafeDeleteFiles( ); // line added 1/15/2011
                        email.Show( );
                    }
                }
            }
            catch( Exception ) { }
            finally {
                SafeDeleteFiles( );
            }
        }


        #region Private Members

        private const string AppName = AssemblyInfo.Title;
        private const string EmailAddress = "weatherspark@gmail.com";
        private const string Separator = "----------------------------------------";

        private static readonly ErrorFileInfo[] Files = new[] {
            new ErrorFileInfo( "LittleWatson.txt", Localized.ErrorSource.Unknown ),
            new ErrorFileInfo( SharedStorage.ErrorFile, Localized.ErrorSource.TileGeneration )
        };

        private static string FileName { get { return Files[0].Key; } }


        private static void SafeDeleteFiles( ) {
            using( var store = IsolatedStorageFile.GetUserStoreForApplication( ) ) {
                foreach( ErrorFileInfo info in Files )
                    SafeDeleteFile( store, info.Key );
            }
        }

        private static void SafeDeleteFile( IsolatedStorageFile store, string fileName ) {
            try {
                store.DeleteFile( fileName );
            }
            catch( Exception ) { }
        }

        #endregion

    }

}
